package com.itheima.reggie.controller;

import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);
        shoppingCart = shoppingCartService.add(shoppingCart);

        return R.success(shoppingCart);
    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        R<List<ShoppingCart>> result = shoppingCartService.findAll(userId);
        return result;
    }

    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);
        shoppingCart = shoppingCartService.sub(shoppingCart);
        return R.success(shoppingCart);
    }

    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        shoppingCartService.clean(userId);

        return R.success("已清空购物车");
    }

}
